package n14_设计模式_固定顺序运行;

import lombok.extern.slf4j.Slf4j;

/**
 * @author fu
 * @date 2022-01-11 21:25
 * 概要：
 * ----------------------------------------------------------------
 * |                                                              |
 * |              固定运行顺序---使用 synchronized 方法             |
 * |                                                             |
 * |=============================================================
 */
@Slf4j(topic = "c.T1")
public class T1_by_synchronized {

    final static Object lock = new Object();
    static boolean t1Started = false;

    public static void main(String[] args) {


        final Thread t1 = new Thread(() -> {

            synchronized (lock){

                while(!t1Started){
                    try {
                        log.debug("t1抢到锁了 进入wait 等t2运行。");
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


                log.debug("-------------- t1 已运行");
            }
        }, "t1");

        final Thread t2 = new Thread(() -> {

            synchronized (lock){
                t1Started = true;
                lock.notifyAll();

                log.debug("============== t2 已运行");
            }

        }, "t2");

        // 运行
        t1.start();
        t2.start();
    }
}
